package com.example.xmlfactory.parse.sax;

import com.example.xmlfactory.parse.ClassMsg;
import com.example.xmlfactory.parse.Parser;
import com.example.xmlfactory.parse.Var;
import com.example.xmlfactory.util.Constant;
import com.example.xmlfactory.util.XMLUtil;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.InputStream;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

/**
 * Created by huangbei on 2017/9/11.
 */

//sax解析器
public class SaxParser extends DefaultHandler implements Parser {

    private List list;
    private StringBuilder builder;

    private ClassMsg classMsg;

    public SaxParser(){
        list = new ArrayList();
        builder = new StringBuilder();
    }

    @Override
    public List parse(InputStream inputStream , Class cl) throws Exception {
        this.classMsg = new ClassMsg(cl);
        //解析inputstream
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(inputStream,this);

        return list;
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        builder.setLength(0);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        builder.append(ch,start,length);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        classMsg.addValue(localName,builder.toString());
        if(localName.equals(classMsg.getClassName())){//一个类解析完成
            list.add(classMsg.generateObj());
        }
    }

}
